package com.szy.news;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import com.szy.news.service.SyncHttp;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleAdapter;

/**
 *@author coolszy
 *@date 2012-2-23
 *@blog http://blog.92coding.com
 */

public class CommentsActivity extends Activity
{
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.common_comments);

		Intent intent = getIntent();
		Bundle bundle = intent.getExtras();
		int nid = bundle.getInt("nid");
		final ArrayList<HashMap<String, Object>> newsList = new ArrayList<HashMap<String, Object>>();
		getNewsComments(nid, newsList);
		SimpleAdapter adapter = new SimpleAdapter(this, newsList, R.layout.comments_list_item, new String[]
		{ "region", "ptime", "content",}, new int[]
		{ R.id.commentator_from, R.id.comment_ptime, R.id.comment_content});
		ListView lv = (ListView) findViewById(R.id.show_comments_list);
		lv.setAdapter(adapter);
	}

	private String getNewsComments(int nid, ArrayList<HashMap<String, Object>> commentsList)
	{
		String url = "http://10.0.2.2:8080/web/getComments";
		String params = "startnid=0&count=10&nid=" + nid;
		SyncHttp syncHttp = new SyncHttp();
		try
		{
			String retString = syncHttp.httpGet(url, params);
			JSONObject jsonObject = new JSONObject(retString);
			int errcode = jsonObject.getInt("errcode");
			if (0 == errcode)
			{
				JSONObject dataObject = jsonObject.getJSONObject("data");
				int totalnum = dataObject.getInt("totalnum");
				if (totalnum > 0)
				{
					JSONArray newslist = dataObject.getJSONArray("commentslist");
					for (int i = 0; i < newslist.length(); i++)
					{
						JSONObject commentsObject = (JSONObject) newslist.opt(i);
						HashMap<String, Object> hashMap = new HashMap<String, Object>();
						hashMap.put("cid", commentsObject.getInt("cid"));
						hashMap.put("ptime", commentsObject.getString("ptime"));
						hashMap.put("region", commentsObject.getString("region"));
						hashMap.put("content", commentsObject.getString("content"));
						hashMap.put("supportCount", commentsObject.getString("supportCount"));
						hashMap.put("opposeCount", commentsObject.getInt("opposeCount"));
						commentsList.add(hashMap);
					}
				}
			}
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}
}
